package com.xuebank.nfe.nfecar.videoplayer

import android.content.Intent
import android.content.res.Configuration
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.widget.FrameLayout

import com.trello.rxlifecycle.components.support.RxAppCompatActivity
import com.wzn.libaray.utils.Logger
import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.xuebank.nfe.nfecar.*
import com.xuebank.nfe.nfecar.R
import com.xuebank.nfe.nfecar.model.VideoModel
import com.xuebank.nfe.nfecar.model.base.BaseModel
import com.xuebank.nfe.nfecar.utils.network.ServiceGenerator
import com.xuebank.nfe.nfecar.utils.network.service.CommonService
import okhttp3.RequestBody
import rx.Observable

import java.io.File
import java.net.URI
import java.net.URISyntaxException

import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.schedulers.Schedulers
import java.util.*
import kotlin.collections.HashMap

/**
 * Base Activity，原生MediaPlayer视频播放器页面基类。
 * 如果要实现自定义UI的视频播放器页面，只需要继承该类，在此基础上实现一个[NativeMediaController.MediaControllerGenerator]接口即可。
 *
 * Created by Anchorer on 2014/9/23.
 */
open class BaseNativeVideoPlayerActivity : RxAppCompatActivity(), SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, NativeMediaController.MediaPlayerControl, NativeMediaController.MediaControllerGenerator {

    private var videoSurface: SurfaceView? = null
    protected var mPlayer: MediaPlayer? = null
    protected var mController: NativeMediaController? = null
    protected var mIntent: Intent? = null
    private var mVideoHolder: SurfaceHolder? = null
    private var mCurrentPosition: Int = 0
    private val map= HashMap<String,RequestBody>()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(R.layout.video_native_activity)
        mIntent = intent

        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt("videoPosition", 0)
        }

        videoSurface = findViewById<SurfaceView>(R.id.video_surface)
        mVideoHolder = videoSurface?.holder
        mVideoHolder?.addCallback(this)

        mController = NativeMediaController(this)
        mController?.setUIGenerator(this)
    }


    override fun generateMediaController(): BaseMediaControllerHolder {
        return BaseMediaControllerHolder()
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        mController?.show()
        return false
    }

    // Implement SurfaceHolder.Callback
    override fun surfaceCreated(holder: SurfaceHolder) {
        try {
            // 创建一个MediaPlayer对象
            mPlayer = MediaPlayer()
            // 设置播放的视频数据源
            mPlayer?.setDataSource(this, Uri.parse(mIntent?.getStringExtra("path")))

            var file: File? = null   //图片地址
            file = File(Uri.parse(mIntent?.getStringExtra("path")).toString())

            uploadVideo(file)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(bindToLifecycle<Any>())
                    .subscribe({
                       Logger.d("it是什么","it是什么   ${it}")
                    },{
                        Logger.e("it是什么","it是什么   ${it}")
                        it.printStackTrace()
                    })


            // 设置AudioStreamType
            mPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
            // 将视频输出到SurfaceView
            mPlayer?.setDisplay(mVideoHolder)
            // 播放准备，使用异步方式，配合OnPreparedListener
            mPlayer?.prepareAsync()
            // 设置相关的监听器
            mPlayer?.setOnPreparedListener(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    fun uploadVideo(file:File): Observable<BaseModel<VideoModel>> {
        Logger.d("cookie","cookie为${SharedPreferencesUtil.getInstance(MyApplication.myApplicationContext).getString(MainActivity.COOKIE)}")
        Logger.d("file的大小","file的大小为${file.length()/1024/1024}")
       return ServiceGenerator.createService(CommonService::class.java)
                .uploadVideo(file=createPartFromFile(file, "file"),pathName=createPartFromString("pathName"))
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}

    override fun surfaceDestroyed(holder: SurfaceHolder) {}

    // Implement VideoMediaCController.MediaPlayerControl
    override fun start() {
        if (mPlayer != null)
            mPlayer?.start()
    }

    override fun pause() {
        if (mPlayer != null)
            mPlayer?.pause()
    }

    override fun getDuration(): Int {
        return if (mPlayer != null) {
            mPlayer?.duration?:0
        } else
            0
    }

    override fun getCurrentPosition(): Int {
        return if (mPlayer != null) {
            mPlayer?.currentPosition?:0
        } else
            0
    }

    override fun seekTo(pos: Int) {
        if (mPlayer != null) {
            mPlayer?.seekTo(pos)
        }
    }

    override fun isPlaying(): Boolean {
        return mPlayer != null && mPlayer?.isPlaying?:true
    }

    override fun getBufferPercentage(): Int {
        return 0
    }

    override fun canPause(): Boolean {
        return true
    }

    override fun canSeekBackward(): Boolean {
        return true
    }

    override fun canSeekForward(): Boolean {
        return true
    }

    override fun isFullScreen(): Boolean {
        return false
    }

    override fun toggleFullScreen() {}
    // End Implement VideoMediaCController.MediaPlayerControl

    // Implement MediaPlayer.OnPreparedListener
    override fun onPrepared(mp: MediaPlayer) {
        mController?.setMediaPlayer(this)
        mController?.setAnchorView(findViewById<View>(R.id.video_surface_container) as FrameLayout)
        mController?.show()
        mPlayer?.start()
        this.seekTo(mCurrentPosition)
        mController?.updatePausePlay()
    }
    // End MediaPlayer.OnPreparedListener

    override fun onPause() {
        super.onPause()
        mCurrentPosition = this.currentPosition
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("videoPosition", mCurrentPosition)
    }

    override fun onDestroy() {
        super.onDestroy()
        releaseMediaPlayer()
    }

    private fun releaseMediaPlayer() {
        if (mPlayer != null) {
            mPlayer?.stop()
            mPlayer?.release()
            mPlayer = null
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
    }
}
